package space.pyq.dlna;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;

import space.core.SystemManager;
import space.service.BeyondUpnpService;
import space.service.SystemService;

/**
 * Created by oo on 2017/9/26.
 */

public class DlnaActivty extends AppCompatActivity {

    public void initDlnaService(){
        // Bind UPnP service
        Intent upnpServiceIntent = new Intent(this, BeyondUpnpService.class);
        bindService(upnpServiceIntent, mUpnpServiceConnection, Context.BIND_AUTO_CREATE);
        // Bind System service
        Intent systemServiceIntent = new Intent(this, SystemService.class);
        bindService(systemServiceIntent, mSystemServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mUpnpServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BeyondUpnpService.LocalBinder binder = (BeyondUpnpService.LocalBinder) service;
            BeyondUpnpService beyondUpnpService = binder.getService();

            SystemManager systemManager = SystemManager.getInstance();
            systemManager.setUpnpService(beyondUpnpService);
            //Search on service created.
            systemManager.searchAllDevices();
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            SystemManager.getInstance().setUpnpService(null);
        }
    };

    private ServiceConnection mSystemServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            SystemService.LocalBinder systemServiceBinder = (SystemService.LocalBinder) service;
            //Set binder to SystemManager
            SystemManager systemManager = SystemManager.getInstance();
            systemManager.setSystemService(systemServiceBinder.getService());
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            SystemManager.getInstance().setSystemService(null);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mUpnpServiceConnection);
        unbindService(mSystemServiceConnection);
        SystemManager.getInstance().destroy();
    }
}
